//
//  LevelPopView.swift
//  FastV
//
//  Created by DC on 2024/6/25.
//

import UIKit

class LevelPopView: UIView {

    @IBOutlet weak var tableView: UITableView!
    
    var currentIndex = 0 {
        didSet {
            tableView.reloadData()
        }
    }
    //回调
    var completion: ((Int)->())?
    // MARK: -- 初始化方法
    static func view() -> LevelPopView {
        let view = Bundle.main.loadNibNamed("LevelPopView", owner: nil, options: nil)?.last as! LevelPopView
        view.setUI()
        return view
    }
    
    // MARK: -- AwakeFromNib
    override class func awakeFromNib() {
        super.awakeFromNib()
    }
    
    // MARK: -- 设置UI
    private func setUI(){
//        backgroundColor = UIColor.black.withAlphaComponent(0.5)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "LevelPopCell", bundle: nil), forCellReuseIdentifier: LevelPopCell.identifier)
        tableView.contentInsetAdjustmentBehavior = .never
    }

    @IBAction func cancelClick(_ sender: UIButton) {
        hidden()
    }
}

// MARK: -- Collection的代理，数据源（扩展）
extension LevelPopView: UITableViewDelegate , UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let arr: [KLevel] = [.Low,.Medium,.High]
        let cell = tableView.dequeueReusableCell(withIdentifier: LevelPopCell.identifier, for: indexPath) as! LevelPopCell
        let l = arr[indexPath.row]
        cell.name.text = l.rawValue
        cell.statusButton.isSelected = indexPath.row == currentIndex
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        currentIndex = indexPath.row
        completion?(currentIndex)
        DispatchQueue.main.asyncAfter(deadline: .now()+2.5, execute: DispatchWorkItem(block: {
            
            self.hidden()
        }))
    }

}


// MARK: -- 扩展
extension LevelPopView {
    
    ///显示
   func show(){
        let win = UIApplication.shared.keyWindow!
        frame = win.bounds
        win.addSubview(self)
        UIView.animate(withDuration: 0.35) {
            self.layer.opacity = 1.0
        }
    }
    ///隐藏
    func hidden(){
       UIView.animate(withDuration: 0.35) {
           self.layer.opacity = 0.0
       } completion: { _ in
           self.removeFromSuperview()
       }
    }
}
